
const { collegeFind } = require('../../../api/index');
const { isFinished, sliceString } = require('../../../utils/util');


// pages/home/index.js
Page({
  /*** 页面的初始数据 */
  data: {
    type: '',
    page: {
      collegeNameLike: '',
      pageNumber: 1,
      pageSize: 20
    },
    total: 0, //  总条数
    finished: false,
    loading: false,
    dataList: [],
    list: []
  },
  //  搜索
  async onSearch(event) {
    this.data.page.collegeNameLike = event.detail;
    this.data.page.pageNumber = 1;
    this.data.list = [];
    this.setData({ finished: false }, () => {
      fetchcollegeFind.call(this);
    });
  },
  loadMore() {
    fetchcollegeFind.call(this);
  },
  onJump(event) {
    const { item } = event.currentTarget.dataset;
    if(this.data.type) {
      //  避免多个页面使用造成干扰
      wx.setStorageSync(this.data.type, item);
    } else {
      wx.setStorageSync('select-school', item);
    }
    
    //  将选择的内容进行缓存处理
    wx.navigateBack();
  },
  /*** 生命周期函数--监听页面加载 */
  onLoad(options) {
    this.data.type = options.type;
    fetchcollegeFind.call(this);
  }
})

//  获取 人才补贴列表
async function fetchcollegeFind() {
  wx.showLoading({ title: '加载中...' });
  const { errors = [], result, totalCount } = await collegeFind( this.data.page );

  if(errors.lenght > 0) {
    return;
  }

  //  判断数据是不是都已经加载完了
  this.setData({ finished: isFinished(totalCount, this.data.page.pageNumber * this.data.page.pageSize ) }); 
  //  加载更多数据
  this.setData({ list: this.data.list.concat( setResult( result )) });
  this.data.page.pageNumber ++;

  wx.hideLoading();
} 

function setResult( data ) {
  const _data = JSON.parse(JSON.stringify( data ));

  _data.map( item => {
    // item.policyContent = sliceString( item.policyContent, 22 );
    return item;
  } )
 
  return _data;
}